package com.cloud.lock.web;

import com.cloud.lock.redis.LockContext;
import com.cloud.lock.redis.Locker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/lock")
@RestController
public class DistributeLockController {


    @Autowired
    private Locker redisLocker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/")
    public String lock() {

        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    LockContext lockContext = redisLocker.getKey("user");
                    if (lockContext != null) {
                        System.out.println(Thread.currentThread().getName() + "获取锁成功!");

                        try {
                            Thread.sleep(100);

                            releaseLock();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println(Thread.currentThread().getName() + "获取锁失败!");
                        try {
                            Thread.sleep(2000);
                            LockContext againLockContext = redisLocker.getKey("user");

                            if (againLockContext != null) {
                                System.out.println(Thread.currentThread().getName() + "获取锁成功!");
                                releaseLock();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                }
            }).start();
        }

        return "success";
    }

    @RequestMapping("/release")
    public String release() {
        releaseLock();

        return "success";
    }

    public void releaseLock() {
        LockContext context = new LockContext();
        context.setKey("lock:user");
        context.setValue(stringRedisTemplate.opsForValue().get("lock:user"));
        redisLocker.releaseLock(context);

        System.out.println(Thread.currentThread().getName() + "释放锁!");
    }

}
